﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class OpenPackage : MonoBehaviour
{
    public GameObject cardPrefab;
    public GameObject cardPool;

    CardStore CardStore;
    List<GameObject> Cards = new List<GameObject>();

    public PlayerData PlayerData;

    private int maxCardLimit = 4;
    // Start is called before the first frame update
    void Start()
    {
        CardStore = GetComponent<CardStore>();
    }

    // Update is called once per frame
    void Update()
    {

    }

    public void OnClinkOpen()
    {

        // 计算还能生成多少张卡牌
        int remainingSlots = maxCardLimit - Cards.Count;

        // 如果没有剩余槽位，则直接返回
        if (remainingSlots <= 0)
        {
            Debug.Log("卡牌数量已达到上限，无法继续生成！");
            return;
        }
        //每次点击扣除2金币
        if (PlayerData.playerCoins < 2)
        {
            return;
        }
        else
        {
            PlayerData.playerCoins -= 2;
        }
        // 只生成不超过剩余槽位数量的卡牌
        int cardsToGenerate = Mathf.Min(3, remainingSlots);

        for (int i = 0; i < cardsToGenerate; i++)
        {
            GameObject newCard = GameObject.Instantiate(cardPrefab, cardPool.transform);

            newCard.GetComponent<CardDisplay>().card = CardStore.RandomCard();

            Cards.Add(newCard);
        }
        SaveCardData();
        PlayerData.SavePlayerData();
    }
    //销毁全部卡牌
    public void ClearPool()
    {
        foreach (var card in Cards)
        {
            Destroy(card);
        }
        if (Cards.Count >= maxCardLimit)
        {
            Cards.Clear();
        }
    }
    public void SaveCardData()
    {
        foreach (var card in Cards)
        {
            int id = card.GetComponent<CardDisplay>().card.id;
            PlayerData.playerCards[id] += 1;
        }
    }
}
